package com.xzzz.irda.guardcat.server.metric.gc;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.xzzz.common.base.util.okhttp.HttpUtil;
import com.xzzz.common.base.util.json.JsonUtil;
import com.xzzz.irda.guardcat.core.constants.GuardcatConstant;
import com.xzzz.irda.guardcat.server.app.pojo.MachineInfo;
import com.xzzz.irda.guardcat.server.metric.MetricFetchJob;
import com.xzzz.irda.guardcat.server.metric.MetricRepository;
import com.xzzz.irda.guardcat.server.metric.Repository;
import com.xzzz.irda.guardcat.server.repos.mysql.GcRepositoryInMySQL;
import lombok.extern.slf4j.Slf4j;

/**
 * 拉取GC指标线程
 *
 * @author xzzz
 */
@Slf4j
@Repository(repo = GcRepositoryInMySQL.class)
public class GcFetchJob extends MetricFetchJob<GcInfo> {

    public GcFetchJob(MachineInfo machineInfo, MetricRepository<GcInfo> metricRepository) {
        super(machineInfo, metricRepository);
    }

    @Override
    public void run() {
        String url;
        long start = System.currentTimeMillis();
        String body = null;

        try {
            url = buildUrl(GuardcatConstant.API.METRIC_JVM_GC);
            body = HttpUtil.get(url);
        } catch (Exception e) {
            long end = System.currentTimeMillis() - start;
            log.error("[GUARDCAT] 从客户端拉取 JVM_GC____ ({}.{}.{}) 失败: {}, 用时:{}",
                    this.machine.getAppName(),
                    this.machine.getMachineId(),
                    this.machine.getIp(),
                    e.getMessage(),
                    end);
        }

        if (StrUtil.isNotBlank(body)) {
            ArrayNode jsonNode = (ArrayNode) JsonUtil.toJsonNode(body);
            try {
                JsonNode ygcNode = jsonNode.get(0);
                GcInfo ygcInfo = getGcNode(ygcNode);
                this.saveAndPublish(ygcInfo);

                JsonNode fgcNode = jsonNode.get(1);
                GcInfo fgcInfo = getGcNode(fgcNode);
                this.saveAndPublish(fgcInfo);
            } catch (Exception e) {
                log.error("[GUARDCAT] 持久化 JVM_GC____ 信息异常: {}", e.getMessage());
            }
        }

    }

    /**
     * 获取 GC 信息
     *
     * @param gcNode gc信息
     */
    private GcInfo getGcNode(JsonNode gcNode) {
        GcInfo gc = new GcInfo();
        if (gcNode != null) {
            gc.setName         (gcNode.get("name").asText());
            gc.setTotalGcCount (gcNode.get("totalGcCount").asLong());
            gc.setTotalGcTime  (gcNode.get("totalGcTime").asLong());
            gc.setGcId         (gcNode.get("lastGcInfo").get("id").asText());
            gc.setStartTime    (gcNode.get("lastGcInfo").get("startTime").asText());
            gc.setCreTime      (gcNode.get("lastGcInfo").get("startTime").asText());
            gc.setEndTime      (gcNode.get("lastGcInfo").get("endTime").asText());
            gc.setDuration     (gcNode.get("lastGcInfo").get("duration").asLong());
        }
        return gc;
    }
}
